<template>
    <div id="imgtext-promote">
      <div  class="img_update">
        <cell class="img-file">
          <div class="img-increase" @click="wxChooseImage">
            <div class="img-choose">
              <img src="../../static/img/shangchuantupian@2x.png"/>
            </div>
            <div class="clear"></div>
          </div>
            <p class="update-img" @click="wxChooseImage"><span>上传图片</span></p>
        </cell>
      </div>
        <tabbar-more>
          <span slot="more" @click="choosemore">更多</span>
          <div slot="title" class="choose_filer">选择模板
            <div class="img_filer_right" v-if="bankFilter">
              <selector  v-model="filterVal" :options="selectorList" @on-change="onChange"></selector>
            </div>
            <div class="img_filer_right" v-if="!bankFilter">
              <div class="filter_val" @click="onClickVal">{{filterVal}}</div>
              <scroller lock-x scrollbar-y  height="300px" v-show="filterShow" class="filter_scroller">
                <div class="box2">
                  <p v-for="(i, index) in selectorList" :key="index" @click="filterClick(index)">{{i}}</p>
                </div>
              </scroller>
            </div>
          </div>
        </tabbar-more>
        <ul class="template-ul">
          <li is="choose-template" v-for="(choose,index) in templatelist"  :i="choose" :keyindex="index" :key="index"></li>
          <div class="clear"></div>
        </ul>
        <load-more v-if="templatelist.length === 0" :show-loading="false" :tip="'暂无模板图片'"  background-color="#fbf9fe"></load-more>
        <div class="circle"></div>
        <tabbar-more>
          <span slot="more" @click="historymore">更多</span>
          <div slot="title">已使用图片</div>
        </tabbar-more>
         <ul class="template-ul use_img">
           <choose-template  v-for="(choose,index) in userimglist"  :i="choose" :keyindex="index" :key="index"></choose-template>
          <div class="clear"></div>
        </ul>
        <load-more v-if="userimglist.length === 0" :show-loading="false" :tip="'暂无历史图片'"  background-color="#fbf9fe"></load-more>
    </div>
</template>
<script>
var timeStamp = String(parseInt(Number(new Date()) / 1000))
import TabbarMore from '../comment/TabbarMore'
import ChooseTemplate from '../comment/ChooseTemplate'
import { Cell, Group, Icon, TransferDom, LoadMore, Scroller, Spinner, Selector } from 'vux'
import api from '../api'
import utils from '../utils'
export default {
  directives: {
    TransferDom
  },
  data () {
    return {
      templatelist: [],
      creditloanlist: [],
      selectorList: ['全部'],
      filterVal: '全部', // 筛选模板图片
      filterShow: false,
      bankFilter: true, // 判断手机和pc端
      result: '',
      ImgUrl: '',
      inputval: '',
      tokenval: '',
      userimglist: [],
      imgtype: null,
      chooseId: '', // 获取筛选的合作方Id
      perNum: 6
    }
  },
  components: {
    Cell,
    Group,
    Icon,
    TabbarMore,
    ChooseTemplate,
    LoadMore,
    Scroller,
    Spinner,
    Selector
  },
  created () {
    window.document.title = '图文推广'
    this.tokenval = utils.AuthToken(timeStamp, this.$store.state.userkey)
    if (((/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i).test(navigator.userAgent))) {
        this.bankFilter = true
    } else {
      this.bankFilter = false
    }
    var historyParams = {
      Tokenuser: this.tokenval,
      userid: this.$store.state.userID,
      timestamp: timeStamp,
      page: 1,
      perPage: 6
    }
    this.apiTemplate(this.chooseId, this.perNum)
    api.userimg(historyParams).then(res => {
      console.log(res)
      this.userimglist = res.data.list
    })
    var paramsed = {
      page: 1,
      perPage: '',
      partnerType: '-1'
    }
    var list = []
    api.creditloan(paramsed).then(res => {
      console.log(res)
      if (res.status === 200) {
        this.creditloanlist = res.data.list
        for (var i in this.creditloanlist) {
          list.push(this.creditloanlist[i].partnerName)
        }
        this.selectorList = this.selectorList.concat(list)
      }
    })
  },
  methods: {
    apiTemplate (partnerId, perNum) {
      var params = {
        Tokenuser: this.tokenval,
        userid: this.$store.state.userID,
        timestamp: timeStamp,
        partnerId: partnerId,
        page: 1,
        perPage: perNum
      }
      api.template(params).then(res => {
        console.log(res, 1)
        this.templatelist = res.data.list
      })
    },
    onClickVal () {
      this.filterShow = !this.filterShow
    },
    filterClick (index) {
      this.filterShow = !this.filterShow
      this.filterVal = this.selectorList[index]
      if (index === 0) {
        this.templatelist = []
        this.chooseId = ''
        this.apiTemplate(this.chooseId, this.perNum)
      } else {
        for (var j in this.creditloanlist) {
          if (this.creditloanlist[j].partnerName === this.selectorList[index]) {
            this.chooseId = this.creditloanlist[j].partnerId
            this.templatelist = []
            this.apiTemplate(this.chooseId, this.perNum)
          }
        }
      }
    },
    onChange (val) {
      this.templatelist = []
      if (val === this.selectorList[0]) {
        this.chooseId = ''
        this.apiTemplate(this.chooseId, this.perNum)
      } else {
        for (var j in this.creditloanlist) {
          if (this.creditloanlist[j].partnerName === val) {
            this.chooseId = this.creditloanlist[j].partnerId
            this.apiTemplate(this.chooseId, this.perNum)
          }
        }
      }
    },
    choosemore () {
      this.$router.push('/picture/template?template_id=' + this.chooseId)
    },
    historymore () {
      this.$router.push('/center/collect')
    },
    /* JSSDK 图片操作 */
    wxChooseImage: function () { // 图片选取
      var self = this
      this.$wechat.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: self.wxUploadImage
      })
    },
    wxUploadImage: function (res) { // 图片上传
      var self = this
      var localIds = res.localIds.toString()
      this.$wechat.uploadImage({
        localId: localIds.toString(),
        isShowProgressTips: 1, // 默认为1，显示进度提示
        success: self.downloadImage
      })
    },
    downloadImage: function (res) {
      var self = this
      var serverId = res.serverId // 返回图片的服务器端ID
      this.$vux.loading.show({text: '图片上传中'})
      var params = {
        token: this.tokenval,
        timestamp: timeStamp,
        userId: this.$store.state.userID,
        imageType: 0,
        wexinMediaId: serverId
      }
      api.upload(params).then(res => {
        if (res.status === '200') {
          self.ImgUrl = res.data.imageUrl
          this.$vux.loading.hide()
          var json = {
            addtaglineimg: self.ImgUrl,
            imagename: '贷款让你快速拿到钱',
            imgpartnerid: '',
            imgid: '',
            logoUrl: '',
            qrCodeLogoIsShow: '',
            imagedesc: '海量借款平台任意选，简单、快速、安全！',
            judge: '1'
          }
          localStorage.setItem('picture', JSON.stringify(json))
          window.location.href = '/picture/slogan'
        }
      })
    }
  }
}
</script>
